package cn.plugins.generator.generate

import cn.plugins.generator.common.FreemarkerConstant
import cn.plugins.generator.entity.TableEntity
import cn.plugins.generator.utils.PrintInfoUtil
import freemarker.template.Configuration
import freemarker.template.Template
import java.io.*
import java.nio.charset.StandardCharsets


/**
 *
 * @描述：生成控制器
 * @时间：2021/3/1 5:27 下午
 * @作者：jy
 * @公司：贵州中测信息技术有限公司
 */
object GenerateController {

    /**
     * 生成controller-freemarker模板
     */
    fun freemarkerGenerate(
        isRestfulStyle: Boolean,
        frameworkType: String,
        config: Configuration,
        projectPath: String,
        packageName: String,
        dic: String,
        languageType: String,
        tableInfo: TableEntity,
        dataMap: MutableMap<String, Any?>
    ) {
        val fileName =
            "${tableInfo.className}Controller.${if (languageType == "java") FreemarkerConstant.JAVA_FILE_SUFFIX else FreemarkerConstant.KOTLIN_FILE_SUFFIX}"
        val fileFullPath =
            "${projectPath}/src/main/${languageType}/${packageName.replace(".", "/")}/${dic}/${fileName}"

        val file = File(fileFullPath)
        if (file.exists()) {
            println("message: file [${fileName}] is exists.")
            return
        }
        if (!file.exists()) {
            file.parentFile.mkdirs()

            PrintInfoUtil.printCreateFold(file.parentFile.absolutePath)
        }

        val template: Template = if (languageType == "java") {
            if (isRestfulStyle) {
                config.getTemplate(
                    "${FreemarkerConstant.BASIC_DIC}/java/$frameworkType/${FreemarkerConstant.RESTFUL_CONTROLLER_TEMPLATE_JAVA}",
                    "UTF-8"
                )
            } else {
                config.getTemplate(
                    "${FreemarkerConstant.BASIC_DIC}/java/$frameworkType/${FreemarkerConstant.CONTROLLER_TEMPLATE_JAVA}",
                    "UTF-8"
                )
            }

        } else {
            config.getTemplate(
                "${FreemarkerConstant.BASIC_DIC}/kotlin/$frameworkType/${FreemarkerConstant.CONTROLLER_TEMPLATE_KOTLIN}",
                "UTF-8"
            )
        }

        val out: Writer = BufferedWriter(OutputStreamWriter(FileOutputStream(fileFullPath), StandardCharsets.UTF_8))
        template.process(dataMap, out)
        out.flush()
        out.close()

        PrintInfoUtil.printCreateFile(fileFullPath)
    }
}